const connection = require('../app/database');

class LabelService {

  // 创建一个标签
  async create(name, userId) {
    try {
      const statement = `INSERT INTO label (name, user_id) VALUES(?, ?)`;
      const result = await connection.execute(statement, [name, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 验证标签是否是自己的
  async isMyLabel(labelId, userId) {
    try {
      const statement = `SELECT * FROM label WHERE id = ? AND user_id = ?`;
      const result = await connection.execute(statement, [labelId, userId]);
      return result[0].length === 0 ? false : true;
    } catch (error) {
      console.log(error);
    }
  }

  // 动态添加标签
  async addLabel(momentId, labelId) {
    try {
      const statement = `INSERT INTO moment_label (moment_id, label_id) VALUES (?, ?)`;
      const result = await connection.execute(statement, [momentId, labelId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 动态移除标签
  async removeLabel(momentId, labelId) {
    try {
      const statement = `DELETE FROM moment_label WHERE moment_id = ? AND label_id = ?`;
      const result = await connection.execute(statement, [momentId, labelId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一个标签
  async remove(labelId) {
    try {
      const statement = `DELETE FROM label WHERE id = ?`;
      const result = await connection.execute(statement, [labelId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 返回全部标签
  async list(userId) {
    try {
      const statement = `SELECT id, name, createAt createTime, updateAt updateTime FROM label WHERE user_id = ?`;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new LabelService();
